package com.ysw.rpc.server.config;

import com.ysw.rpc.server.component.ApplicationContextComponent;
import io.netty.channel.Channel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultThreadFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author YinShangwen
 * @since 2023/4/18 10:11
 */
public abstract class AbstractServerInitializerConfig implements ApplicationContextAware, DisposableBean {
    private final NioEventLoopGroup parent;
    private final NioEventLoopGroup worker;
    private Channel channel;

    public AbstractServerInitializerConfig() {
        this.parent = new NioEventLoopGroup(2, new DefaultThreadFactory("y-rpc-parent", true));
        this.worker = new NioEventLoopGroup(new DefaultThreadFactory("y-rpc-worker", true));
    }

    /**
     * 初始化服务端
     */
    public abstract void initServer();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextComponent.set(applicationContext);
        initServer();
    }

    @Override
    public void destroy() {
        channel.close();
    }

    public void closeEventLoopGroup() {
        parent.shutdownGracefully();
        worker.shutdownGracefully();
    }


    public NioEventLoopGroup getParent() {
        return parent;
    }

    public NioEventLoopGroup getWorker() {
        return worker;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }
}
